package com.exam.commonbiz.util;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.IOException;

public class AvatarUtils {
    // 请求码
    public static final int REQUEST_CAMERA = 1001;
    public static final int REQUEST_GALLERY = 1002;
    public static final int REQUEST_CROP = 1003;

    // 临时文件
    public static File tempCameraFile;
    private static File tempCropFile;

    // 显示选择对话框
    public static void showAvatarDialog(Activity activity) {
        String[] items = {"拍照", "从相册选择"};
        new AlertDialog.Builder(activity)
                .setTitle("设置头像")
                .setItems(items, (dialog, which) -> {
                    if (which == 0) {
                        // 拍照
                        checkCameraPermission(activity);
                    } else {
                        // 相册
                        checkStoragePermission(activity);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }

    // 检查相机权限
    private static void checkCameraPermission(Activity activity) {
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions = new String[]{Manifest.permission.CAMERA};
        } else {
            permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }

        if (PermissionUtils.checkAndRequestPermissions(activity, permissions, REQUEST_CAMERA)) {
            openCamera(activity);
        }
    }

    // 检查存储权限
    private static void checkStoragePermission(Activity activity) {
        String permission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permission = Manifest.permission.READ_MEDIA_IMAGES;
        } else {
            permission = Manifest.permission.READ_EXTERNAL_STORAGE;
        }

        if (PermissionUtils.checkAndRequestPermissions(activity, new String[]{permission}, REQUEST_GALLERY)) {
            openGallery(activity);
        }
    }

    // 打开相机
    private static void openCamera(Activity activity) {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

            // 确保有相机应用可以处理该Intent
            if (intent.resolveActivity(activity.getPackageManager()) != null) {
                // 创建临时文件
                tempCameraFile = createTempFile(activity, "camera_photo", ".jpg");

                // Android 7.0+ 使用FileProvider
                Uri photoUri = FileProvider.getUriForFile(
                        activity,
                        activity.getPackageName() + ".pgyer.fileprovider",
                        tempCameraFile);
                // 授予临时权限
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

                // 指定输出位置
                intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                activity.startActivityForResult(intent, REQUEST_CAMERA);
            } else {
                Toast.makeText(activity, "没有可用的相机应用", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zdddz", e.getMessage());
            Toast.makeText(activity, "无法打开相机", Toast.LENGTH_SHORT).show();
        }
    }

    // 打开相册
    private static void openGallery(Activity activity) {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        activity.startActivityForResult(intent, REQUEST_GALLERY);
    }

    // 创建临时文件
    private static File createTempFile(Context context, String prefix, String suffix) throws IOException {
//        File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File storageDir = context.getFilesDir();
        if (storageDir == null) {
            storageDir = context.getFilesDir();
        }
        // 确保目录存在
        if (!storageDir.exists()) {
            storageDir.mkdirs();
        }
        return File.createTempFile(prefix, suffix, storageDir);
    }

    // 处理Activity结果
    public static void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data,
                                        OnAvatarSelectedListener listener) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }

        switch (requestCode) {
            case REQUEST_CAMERA:
                if (tempCameraFile != null && tempCameraFile.exists()) {
                    startCrop(activity, Uri.fromFile(tempCameraFile));
                }
                break;

            case REQUEST_GALLERY:
                if (data != null && data.getData() != null) {
                    startCrop(activity, data.getData());
                }
                break;

            case REQUEST_CROP:
                if (tempCropFile != null && tempCropFile.exists()) {
                    if (listener != null) {
                        listener.onAvatarSelected(tempCropFile);
                    }
                }
                break;
        }
    }

    // 处理权限请求结果
    public static void onRequestPermissionsResult(Activity activity, int requestCode,
                                                  String[] permissions, int[] grantResults,
                                                  OnAvatarSelectedListener listener) {
        if (PermissionUtils.verifyPermissions(grantResults)) {
            switch (requestCode) {
                case REQUEST_CAMERA:
                    openCamera(activity);
                    break;
                case REQUEST_GALLERY:
                    openGallery(activity);
                    break;
            }
        } else {
            Toast.makeText(activity, "权限被拒绝", Toast.LENGTH_SHORT).show();
        }
    }

    // 启动裁剪
    private static void startCrop(Activity activity, Uri sourceUri) {
        //        try {
//            tempCropFile = createTempFile(activity, "crop_photo", ".png");
//            Uri outputUri = Uri.fromFile(tempCropFile);
//
//            // 使用系统裁剪工具
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.putExtra("uri", sourceUri);
//            intent.setDataAndType(sourceUri, "image/*");
//            intent.putExtra("crop", "true");
//            intent.putExtra("aspectX", 1);
//            intent.putExtra("aspectY", 1);
//            intent.putExtra("outputX", 300);
//            intent.putExtra("outputY", 300);
//            intent.putExtra("scale", true);
//            intent.putExtra("return-data", false);
//            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
//            intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
//
//            // 授予临时权限
//            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
//
            activity.startActivityForResult(intent, REQUEST_CROP);
//        } catch (Exception e) {
//            Toast.makeText(activity, "无法裁剪图片", Toast.LENGTH_SHORT).show();
//            e.printStackTrace();
//        }
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    public static Bitmap getBitmapFromMediaStore(Context context, Uri uri) {
        try {
            ContentResolver resolver = context.getContentResolver();
            // 获取图片信息
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = resolver.query(uri, projection, null, null, null);

            if (cursor != null && cursor.moveToFirst()) {
                // 从 MediaStore 获取 Bitmap
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inPreferredConfig = Bitmap.Config.RGB_565;
                return MediaStore.Images.Media.getBitmap(resolver, uri);
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static File uriToFile(Context context, Uri uri) {
        if (uri == null) return null;

        // 1. 处理 file:// Uri
        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            return new File(uri.getPath());
        }

        // 2. 处理 content:// Uri
        if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            String[] projection = {MediaStore.Images.Media.DATA};
            Cursor cursor = null;

            try {
                cursor = context.getContentResolver().query(uri, projection, null, null, null);
                if (cursor != null && cursor.moveToFirst()) {
                    int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    String filePath = cursor.getString(columnIndex);
                    if (filePath != null) {
                        return new File(filePath);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }

        return null;
    }

    public interface OnAvatarSelectedListener {
        void onAvatarSelected(File avatarFile);
    }
}